import { acceptHMRUpdate, defineStore } from 'pinia'
import { store } from '../index'
import { storageLocal } from '@/utils/storage'
import { decodeAES, encodeAES, aesKey, iv } from '@/utils/aesRsa'
import { StorageEnum } from '@/enums/storageEnums'

export const useUserInfoStore = defineStore('userInfo', () => {
  const { CK_USER_INFO_STORE } = StorageEnum
  const userInfo = ref(null)

  const getUserInfoCache = () => {
    if (storageLocal.getItem(CK_USER_INFO_STORE)) {
      userInfo.value = JSON.parse(decodeAES(storageLocal.getItem(CK_USER_INFO_STORE), aesKey, iv))
    }
  }

  const setUserInfoCache = () => {
    storageLocal.setItem(CK_USER_INFO_STORE, encodeAES(userInfo.value, aesKey, iv))
  }

  const removeUserInfoCache = () => {
    storageLocal.removeItem(CK_USER_INFO_STORE)
    setTimeout(() => {
      userInfo.value = null
    }, 100)
  }

  return {
    userInfo,
    getUserInfoCache,
    setUserInfoCache,
    removeUserInfoCache
  }
})

if (import.meta.hot) {
  import.meta.hot.accept(acceptHMRUpdate(useUserInfoStore, import.meta.hot))
}

export const useUserInfoStoreWithOut = () => {
  return useUserInfoStore(store)
}
